//
//  JFBaseWebViewController.m
//  JFBase
//
//  Created by Alan Wang on 2018/8/22.
//  Copyright © 2018年 Alan Wang. All rights reserved.
//

#import "JFBaseWebViewController.h"
#import <UIKit/UIKit.h>

//依赖第三方
//#if __has_include(<WebViewJavascriptBridge/wk.h>)
//#import <WebViewJavascriptBridge/wkwe.h>
//#else
//#import "WebViewJavascriptBridge.h"
//#endif
#import "WKWebViewJavascriptBridge.h"

//依赖的工具类
#import "JFStringHelper.h"
//模块调用相关
#import "JFMsgCenterVo.h"
#import "JFMsgCenteManager.h"
#import "JFBaseMsgModuleManager.h"
#import "UIImage+BaseBuddle.h"


#import<AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

#import "JFWeakScriptMessageDelegate.h"
#import "JFBasePri.h"
#import <Contacts/Contacts.h>
#import "JFBasePri.h"


@implementation AWWebViewConfiguration
-(instancetype)init{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor colorWithHexString:@"#F5F5F5"];
        self.progressColor = [UIColor blueColor];
        self.webViewBackgroundColor = [UIColor colorWithHexString:@"#F5F5F5"];
        self.progressBackgroundColor = [UIColor grayColor];
        self.progressTintColor = [UIColor colorWithHexString:@"#FC724C"];
        self.endableJavascriptBridge = YES;
    }
    return self;
}
@end


@interface JFBaseWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong) UIProgressView * progressView;
@property(nonatomic,assign) CGFloat  lastProgress;
@property(nonatomic,strong) WKWebViewJavascriptBridge * bridge;
@property(nonatomic,strong) WKNavigation * backNav;

@property (nonatomic,strong) UIImagePickerController *pickerVC;

@property (nonatomic, assign) CGPoint keyBoardPoint;


@property (nonatomic,copy) NSString *shareUrl;
@property (nonatomic,copy) NSString *shareTitle;
@property (nonatomic,copy) NSString *shareContent;
@property (nonatomic,copy) NSString *shareImageUrl;
@property (nonatomic,copy) NSString *shareAimList;
@property (nonatomic,assign) BOOL  isShowImage;

@end

@implementation JFBaseWebViewController
-(instancetype)init{
    self = [super init];
    if (self) {
        self.backStyle = JFWebLeftItemStyleClose|JFWebLeftItemStyleBack;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatLeftBtn];



    if(!self.config){
        self.config = [[AWWebViewConfiguration alloc] init];
    }
    if([JFStringHelper isNotEmpty:self.webtitle]){
        self.navigationItem.title = self.webtitle;
    }
    switch (_type) {
        case AWWEBVIEW_TYPE_WKWEBVIEW:
        {
            [self creatWKWebview];
            [self.view addSubview:self.progressView];
        }break;
        default:
            [self creatWKWebview];
            [self.view addSubview:self.progressView];
            break;
    }

    self.view.backgroundColor = self.config.backgroundColor;
    self.progressView.backgroundColor = self.config.progressBackgroundColor;
    self.progressView.progressTintColor = self.config.progressTintColor;

    if(self.bridge){
        [self.bridge registerHandler:@"AWCallNative" handler:^(id data, WVJBResponseCallback responseCallback) {
            if(data){
                NSString * requestNum = data[@"requestNum"];
                NSDictionary * params = data[@"params"];
                BOOL sync = [data[@"sync"] boolValue];
                if(sync){
                    JFMsgCenterVo * msgCenter = [[JFMsgCenterVo alloc] init];
                    msgCenter.requestNum = requestNum;
                    msgCenter.params = params;
                    //调用插件
                    msgCenter = [JFMsgCenteManager requestWithMsgCenterVo:msgCenter callback:^(JFResultVo *resultVo) {
                    }];
                    responseCallback(msgCenter.params);
                }else{

                    JFMsgCenterVo * msgCenter = [[JFMsgCenterVo alloc] init];
                    msgCenter.requestNum = requestNum;
                    msgCenter.params = params;
                    msgCenter.callback = ^(JFResultVo *resultVo) {
                       responseCallback(resultVo.results);
                    };
                    [JFMsgCenteManager requestWithMsgCenterVo:msgCenter callback:^(JFResultVo *resultVo) {

                    }];
                }
            }

        }];

        [self registerOldFunc];
    }
    



    [self reloadUrl:self.urlStr];
    
    //注册通知
    [self registrationNotice];
}
-(void)registrationNotice{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didCaptureItem:) name:@"_UIImagePickerControllerUserDidCaptureItem" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRejectItem:) name:@"_UIImagePickerControllerUserDidRejectItem" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow) name:UIKeyboardWillShowNotification object:nil];
    /// 监听将要隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden) name:UIKeyboardWillHideNotification object:nil];
    //上传分享资讯上传
}
//分享结束
-(void)shareEndNoti{
    if (self.shareUrl) {
        if ([self.shareUrl rangeOfString:@"newid="].location != NSNotFound) {
            NSString *parameter = [self.shareUrl componentsSeparatedByString:@"?"].lastObject;
            NSArray *array = [parameter componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"=&"]];
            NSInteger index = [array indexOfObject:@"newid"];
            NSString *rid = (array.count > index + 2) ? array[index + 1] : @"";
            [JFBaseRequestHelper getRewardPointsWithType:@"6" rid:rid callBack:^(JFResultVo *resultVo) {
                
            }];
        };
    }
}


-(void)reloadUrl{
  [self reloadUrl:self.urlStr];
}

-(void)registerOldFunc{
    
    AWWeakSelf(self)

    [self.bridge registerHandler:@"functionName" handler:^(id data, WVJBResponseCallback responseCallback)
     {

         //跳转方法
         SEL func = NSSelectorFromString(data[@"functionName"]);
         if ([weakself respondsToSelector:func]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
             id obj = [weakself performSelector:func withObject:nil];
             if (obj) {
                 responseCallback(obj);
             }
#pragma clang diagnostic pop
         }

     }];



    [self.bridge registerHandler:@"JFNewClient" handler:^(id data, WVJBResponseCallback responseCallback)
     {

         //取方法名
         NSString * functionName = data[@"function"];
         //取参数
         NSDictionary * params = data[@"data"];
         if (params.count) {
             functionName = [NSString stringWithFormat:@"%@:",functionName];
         }
         //跳转方法
         SEL func = NSSelectorFromString(functionName);

         if ([weakself respondsToSelector:func]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
             id obj = [weakself performSelector:func withObject:params];
             if (obj) {
                 responseCallback(obj);
             }
#pragma clang diagnostic pop
         }

     }];

    //获取拍照获取相册
    [self.bridge registerHandler:@"getAppleCam" handler:^(id data, WVJBResponseCallback responseCallback) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(),
                           ^{

                //相机
                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
                    authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
                {
                    // 无权限 引导去开启
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url];
                    }
                }
                
                
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
                    
                    NSDictionary *dic = data;
                    
                    weakself.pickerVC = [[UIImagePickerController alloc] init];
                    weakself.pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                    weakself.pickerVC.delegate = weakself;
                    weakself.pickerVC.modalPresentationStyle = UIModalPresentationCurrentContext;
                    if ([dic[@"type"] boolValue]) {
                        
                        NSInteger type = [dic[@"idCardFace"] integerValue];
                        
                        if ([dic[@"tips"] length]) {
                            weakself.pickerVC.cameraOverlayView = [weakself CameraOverlayView:dic[@"tips"] type:type];
                            
                        }
                        else{
                            weakself.pickerVC.cameraOverlayView = [weakself CameraOverlayView:nil type:type];
                        }
                        
                    }
                    weakself.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                    [weakself presentViewController:weakself.pickerVC animated:YES completion:nil];
                    
                }else{
                    [weakself.bridge callHandler:@"picUpload" data:@{@"pic":@""} responseCallback:^(id response) {

                    }];
                    [weakself.bridge callHandler:@"JFNewClient_Back" data:@{
                                                                      
                                                                      @"msg":@"useSysCamera:ok",
                                                                      @"data":@""
                                                                      
                                                                      } responseCallback:^(id responseData)
                     {
                         
                     }];
                    
                }
  
            });
        });


    }];


    //身份证扫描
    [self.bridge registerHandler:@"getSTIDCardModule" handler:^(id data, WVJBResponseCallback responseCallback) {

        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"APP";
        msg.requestNum = @"000001";
        msg.params = data;
        msg.callback = ^(JFResultVo *resultVo) {
            [weakself.bridge callHandler:@"getSTIDCardModule" data:resultVo.results responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {

        }];

    }];

    //银行卡扫描
    [self.bridge registerHandler:@"getSTBankCardModule" handler:^(id data, WVJBResponseCallback responseCallback) {

        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"APP";
        msg.requestNum = @"000002";
        msg.params = data;
        msg.callback = ^(JFResultVo *resultVo) {
            [weakself.bridge callHandler:@"getSTBankCardModule" data:resultVo.results responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {

        }];

    }];

    //活体检测
    [self.bridge registerHandler:@"getSTLivenessModule" handler:^(id data, WVJBResponseCallback responseCallback) {

        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"APP";
        msg.requestNum = @"000003";
        msg.params = data;
        msg.callback = ^(JFResultVo *resultVo) {
            [weakself.bridge callHandler:@"getSTLivenessModule" data:resultVo.results responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {

        }];
    }];


    //初始化CA证书
    [self.bridge registerHandler:@"initSZCA" handler:^(id data, WVJBResponseCallback responseCallback) {
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"APP";
        msg.requestNum = @"000004";
        msg.params = data;
        msg.callback = ^(JFResultVo *resultVo) {
            [weakself.bridge callHandler:@"initSZCA" data:resultVo.results responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {

        }];
    }];
    //对文件签名
    [self.bridge registerHandler:@"signingCADoc" handler:^(id data, WVJBResponseCallback responseCallback) {

        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"APP";
        msg.requestNum = @"000005";
        msg.params = data;
        msg.callback = ^(JFResultVo *resultVo) {
            [weakself.bridge callHandler:@"signingCADoc" data:resultVo.results responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {

        }];
    }];

    [self.bridge registerHandler:@"reloadUrlWithData" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *  tempurl = data[@"url"];
        if(tempurl&&tempurl.length){
            weakself.urlStr = tempurl;
            [weakself reloadUrl];
        }
    }];

    //校验令牌
    [self.bridge registerHandler:@"checkTokenState" handler:^(id data, WVJBResponseCallback responseCallback) {
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"APP";
        msg.requestNum = @"000006";
        msg.callback = ^(JFResultVo *resultVo) {
            [weakself.bridge callHandler:@"checkTokenState" data:resultVo.results responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {
        }];
    }];


    [self.bridge registerHandler:@"tradeUnlock" handler:^(id data, WVJBResponseCallback responseCallback) {
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"STOCK";
        msg.requestNum = @"800008";
        msg.callback = ^(JFResultVo *resultVo) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:3];
            dic[@"msg"] = @"tradeUnlock:ok";
            dic[@"data"] = resultVo.results;
            [weakself.bridge callHandler:@"tradeUnlock" data:dic responseCallback:^(id response) {

            }];
        };
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {
        }];
    }];

    //赠股分享
    [self.bridge registerHandler:@"giftStockShare" handler:^(id data, WVJBResponseCallback responseCallback) {
        AWStrongSelf(weakself)
        [strongself giftStockShare:(NSDictionary*)data];
    }];

    //获取通讯录联系人
    [self.bridge registerHandler:@"addressBookPeopleList" handler:^(id data, WVJBResponseCallback responseCallback) {
        AWStrongSelf(weakself)
        [strongself addressBookPeopleList];
    }];
    
    //H5 通知交易密码已经重置
    [self.bridge registerHandler:@"resetTradePwd" handler:^(id data, WVJBResponseCallback responseCallback) {
       JFMsgCenterVo * msg2 = [[JFMsgCenterVo alloc] init];
       msg2.from = @"BASE";
       msg2.to = @"STOCK";
       msg2.requestNum = @"800008";
       msg2.params=@{@"type":@(11)};
       msg2.callback = ^(JFResultVo *resultVo) {
           [weakself.bridge callHandler:@"resetTradePwd" data:resultVo.results responseCallback:^(id response) {
                              
           }];
       };
       [JFMsgCenteManager requestWithMsgCenterVo:msg2 callback:nil];
    }];
}
//调用js的方法
-(void)callJS:(NSString*)method  data:(id)data  responseCallback:(AWCallJSResponseCallback)block{
    if(self.bridge){
        if([JFStringHelper isNotEmpty:method]){
            [self.bridge callHandler:method data:data responseCallback:block];
        }else{
            if(block){
                block(@{@"errorNo":@"-2",@"errorInfo":@"调用的js方法不能为空"});
            }
        }

    }else{
        if(block){
            block(@{@"errorNo":@"-1",@"errorInfo":@"未找到与js交互的桥"});
        }
    }
}
//加载本地的html
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL{
    switch (_type) {
        case AWWEBVIEW_TYPE_WKWEBVIEW:
        {
            [self.wkWebView loadHTMLString:string baseURL:baseURL];
        }break;
        default:{
            [self.wkWebView loadHTMLString:string baseURL:baseURL];
        }
            
            break;
    }
}
-(void)setHideNav:(BOOL)hideNav{
    _hideNav = hideNav;
    CGFloat offset = self.bottomOffset;
    if (kDevice_Is_iPhoneX) {
        if (hideNav) {
            offset = self.bottomOffset + BottomSafeHeight;
        }else{
            offset = self.bottomOffset + NavBarAndBottomHeight;
        }
    }else{
        if(hideNav){
            offset = self.bottomOffset;
        }else{
            offset = self.bottomOffset + NavBarHeight;
        }
    }
    CGRect rect = CGRectMake(0,0,AWSCREEN_WIDTH, AWSCREENH_HEIGHT-offset);
    if(self.wkWebView){
        self.wkWebView.frame = rect;
    }  
}
-(void)creatWKWebview{
    [self.view addSubview:self.wkWebView];
    self.wkWebView.backgroundColor = self.config.webViewBackgroundColor;
    CGFloat offset = self.bottomOffset;
    
    if (kDevice_Is_iPhoneX) {
        if (self.hideNav) {
             offset = self.bottomOffset + BottomSafeHeight;
        }else{
             offset = self.bottomOffset + NavBarAndBottomHeight;
        }
    }else{
        if(self.hideNav){
            offset = self.bottomOffset;
        }else{
            offset = self.bottomOffset + NavBarHeight;
        }
    }
    WEAKSELF
    [self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        
        NSString * benben = [JFDeviceInfo isBenBen]?@"sunline-iOS":@"sunline_custom-iOS";
        NSString *userAgent = result;
        if ([userAgent rangeOfString:benben].location != NSNotFound) {
            return ;
        }
        NSString *newUserAgent = [NSString stringWithFormat:@"%@\\%@-%@",
                                  userAgent,
                                  benben,[JFDeviceInfo appVersion]];
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : newUserAgent, @"User-Agent" : newUserAgent}];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (@available(iOS 9.0, *)) {
            [weakSelf.wkWebView setCustomUserAgent:newUserAgent];
        } else {
            [weakSelf.wkWebView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
        }
     }];
 

    CGRect rect = CGRectMake(0,0,AWSCREEN_WIDTH, AWSCREENH_HEIGHT-offset);
    self.wkWebView.frame = rect;
    if (@available(iOS 11.0, *)) {
        self.wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (self.config.endableJavascriptBridge) {
        self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.wkWebView];
    }
    
    [self.bridge setWebViewDelegate:self];

}
-(void)reloadUrl:(NSString*)url{
    if([JFStringHelper isEmpty:url]){
        return;
    }
    NSString * tempUrl = url;
    if (![url hasPrefix:@"http"]) {//是否具有http前缀
        tempUrl = [NSString stringWithFormat:@"http://%@",url];
    }
    NSLog(@"当前加载Uri:%@",tempUrl);
    AWWeakSelf(self);
    dispatch_async(dispatch_get_main_queue(),^{
        NSString * UrlStr = tempUrl;
        NSString *encodedString = [UrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`%^{}\"[]|\\<> "].invertedSet];
        UrlStr = encodedString;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:UrlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.f];
        [request setValue:@"com.sunline.iossunline://" forHTTPHeaderField:@"Referer"];
        [weakself.wkWebView loadRequest:request];
    });
}

- (UIProgressView *)progressView
{
    if (!_progressView)
    {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, AWSCREEN_WIDTH, 1)];
    }
    return _progressView;
}
-(WKWebView*)wkWebView{
    
    if(!_wkWebView){
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.selectionGranularity = YES;
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        // 是否支持记忆读取
        config.suppressesIncrementalRendering = YES;
        config.preferences = [[WKPreferences alloc]init];
        WKUserContentController* userContent = [[WKUserContentController alloc] init];
        [userContent addScriptMessageHandler:[[JFWeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"AWCallNative"];
        config.userContentController = userContent;
        WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:config];
        webView.navigationDelegate = self;
        webView.UIDelegate = self;
        //添加此属性可触发侧滑返回上一网页与下一网页操作
        webView.allowsBackForwardNavigationGestures = NO;
        webView.scrollView.bounces = NO;
        webView.opaque = NO;
        [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
        [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
        _wkWebView = webView;
    }
      _wkWebView.backgroundColor = self.view.backgroundColor;
    return _wkWebView;
}
-(void)registerUserAgent{
    
}
#pragma mark--辅助方法
-(void)creatLeftBtn{
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    if (self.backStyle & JFWebLeftItemStyleBack) {
        [arr addObject:[self backBarButtonItem]];
    }
    if (self.backStyle & JFWebLeftItemStyleClose){
          [arr addObject:[self closeBarButtonItem]];
    }
    self.navigationItem.leftBarButtonItems = [arr copy];
    if (!arr.count) {
        self.navigationItem.leftBarButtonItem = nil;
        self.navigationItem.backBarButtonItem = nil;
        [self.navigationController.navigationItem setHidesBackButton:YES];
        [self.navigationItem setHidesBackButton:YES];
        [self.navigationController.navigationBar.backItem setHidesBackButton:YES];
    }
}


-(void)cusBack:(UIBarButtonItem*)item{
    if ([_wkWebView canGoBack]) {
        if(self.bridge){
            [self.bridge callHandler:@"onGoBack"];
        }
        _backNav = [_wkWebView goBack];
    } else {
        if(self.navigationController.presentingViewController){
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
             [self back];
        }
       
    }
}
-(void)close:(UIBarButtonItem*)item{
    if(self.navigationController.presentingViewController){
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self back];
    }
}
- (UIBarButtonItem*)backBarButtonItem {
       NSString * imageName = @"topbtn_back";
        if ([@"White" isEqualToString:[AWThemeManager shareInstance].skinName]) {
          imageName = @"topbtn_back_w";
        }
    
        UIButton * button = [self.navigationItem creatBtn];
        UIImage* backItemImage = [UIImage imageNameFromBaseBuddle:imageName];
        [self.navigationItem setLeftImage:button image:backItemImage];
        [button setTitleColor:HexColor(@"#ffffff") forState:UIControlStateNormal];
        [button addTarget:self action:@selector(cusBack:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        return backBarButtonItem;
}

- (UIBarButtonItem*)closeBarButtonItem {
    NSString * imageName = @"topbtn_close";
    if ([@"White" isEqualToString:[AWThemeManager shareInstance].skinName]) {
        imageName = @"topbtn_close_w";
    }
    UIButton * button = [self.navigationItem creatBtn];
    UIImage* backItemImage = [UIImage imageNameFromBaseBuddle:imageName];
    [self.navigationItem setLeftImage:button image:backItemImage];
    [button setTitleColor:HexColor(@"#ffffff") forState:UIControlStateNormal];
    [button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    return backBarButtonItem;
}
-(void)updateProgress:(double)progress{
    self.progressView.alpha = 1;
    if(progress > _lastProgress){
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:YES];
    }else{
        [self.progressView setProgress:self.wkWebView.estimatedProgress];
    }
    _lastProgress = progress;
    
    if (progress >= 1) {
        AWWeakSelf(self)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakself.progressView.alpha = 0;
            [weakself.progressView setProgress:0];
            weakself.lastProgress = 0;
        });
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    AWWeakSelf(self)
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        self.progressView.progress = self.wkWebView.estimatedProgress;
        if (self.progressView.progress == 1)
        {
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^
             {
                 weakself.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
             }
                             completion:^(BOOL finished)
             {
                 weakself.progressView.hidden = YES;
             }];
        }
    }
    
    if ([keyPath isEqualToString:@"title"]){
        NSString *title = change[@"new"];
        if (!(title == nil || title.length == 0 || [title isEqualToString:@"weixin"])) {
            if(!_webtitle){
                self.navigationItem.title = title;
            }else{
                self.navigationItem.title = self.webtitle;
            }
            
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
}
#pragma mark - WKNavigationDelegate
//页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    webView.hidden = NO;
    self.progressView.hidden = NO;
    if ([webView.URL.scheme isEqual:@"about"]) {
        webView.hidden = YES;
    }
}

//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{


}
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    [webView reload];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {

    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];

    if(([strRequest isEqualToString:_urlStr])||([strRequest isEqualToString:[_urlStr stringByRemovingPercentEncoding]])) {//主页面加载内容
        decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
    } else {//截获页面里面的链接点击
        NSURL *URL = navigationAction.request.URL;
        NSString *scheme = [URL scheme];
        if ([scheme isEqualToString:@"tel"]) {
                NSString *resourceSpecifier = [URL resourceSpecifier];
                NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
                decisionHandler(WKNavigationActionPolicyCancel);//允许跳转
                return;
        }
        if ([[URL absoluteString] rangeOfString:@"wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?"].length >0) {
              NSMutableURLRequest * request = [navigationAction.request mutableCopy];
              NSDictionary * dict = request.allHTTPHeaderFields;
              NSString * referer = [dict stringForKey:@"Referer"];
               if([JFStringHelper isEmpty:referer]){
                   
                NSString *scheme = nil;
                if([JFEnvironmentManager isPro]){
                            scheme = @"pay.9fbenben.com://";
                }else{
                            scheme = @"test.9fbenben.com://";
                }
                [request setValue:scheme forHTTPHeaderField:@"Referer"];
                [self.wkWebView loadRequest:request];
                   
               }
            decisionHandler(WKNavigationActionPolicyAllow);//不允许跳转
            return;
        }else if([scheme isEqualToString:@"pay.9fbenben.com"] || [scheme isEqualToString:@"test.9fbenben.com"]){
            [self.wkWebView goBack];
            decisionHandler(WKNavigationActionPolicyCancel);//允许跳转
            return;
        }else{
            if ([[URL absoluteString] rangeOfString:@"weixin://"].length >0){
                NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
                [mutableRequest.allHTTPHeaderFields setValue:@"com.sunline.iossunline://" forKey:@"Referer"];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL.absoluteString]];
                decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
                return ;
            }
        }
        
        decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
    }
}

//页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    webView.hidden = YES;
}
//HTTPS认证
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
}

#pragma mark--兼容老版本的h5方法
-(void)addressBookPeopleList{
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        WEAKSELF
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
            if (error) {
                //                NSLog(@"授权失败");
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                dic[@"msg"] = @"addressBookPeopleList:ok";
                NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
                params[@"code"] = @"0";
                params[@"codemsg"] = @"授权失败";
                dic[@"data"] = params;
                [weakSelf.bridge callHandler:@"addressBookPeopleList" data:dic responseCallback:^(id response) {
                    
                }];
            }else {
                NSLog(@"成功授权");
                [weakSelf openContact];
            }
        }];
    }
    else if(status == CNAuthorizationStatusRestricted)
    {
        NSLog(@"用户拒绝");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"msg"] = @"addressBookPeopleList:ok";
        NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
        params[@"code"] = @"1";
        params[@"codemsg"] = @"用户拒绝";
        dic[@"data"] = params;
        [self.bridge callHandler:@"addressBookPeopleList" data:dic responseCallback:^(id response) {
            
        }];
        
    }
    else if (status == CNAuthorizationStatusDenied)
    {
        NSLog(@"用户拒绝");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"msg"] = @"addressBookPeopleList:ok";
        NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
        params[@"code"] = @"1";
        params[@"codemsg"] = @"用户拒绝";
        dic[@"data"] = params;
        [self.bridge callHandler:@"addressBookPeopleList" data:dic responseCallback:^(id response) {
            
        }];
        
    }
    else if (status == CNAuthorizationStatusAuthorized)//已经授权
    {
        //有通讯录权限-- 进行下一步操作
        [self openContact];
    }
}

- (void)openContact{
    // 获取指定的字段,并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    NSMutableArray * bookData = [[NSMutableArray alloc]init];
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
        NSMutableArray * phoneList = [[NSMutableArray alloc] init];
        
        //拼接姓名
        NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        NSArray *phoneNumbers = contact.phoneNumbers;
        for (CNLabeledValue *labelValue in phoneNumbers) {
            CNPhoneNumber *phoneNumber = labelValue.value;
            NSString * string = phoneNumber.stringValue ;
            //去掉电话中的特殊字符
            string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            if (string) {
                NSString *pureNumbers = [[string componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]] componentsJoinedByString:@""];
                [phoneList addObject:pureNumbers];
            }
        }
        dict[@"name"] = nameStr;
        dict[@"phoneList"] = phoneList;
        
        if((nameStr && nameStr.length >0) && phoneList.count ){
            [bookData addObject:dict];
        }
        
    }];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"msg"] = @"addressBookPeopleList:ok";
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    params[@"code"] = @"2";
    params[@"codemsg"] = @"用户同意";
    params[@"bookData"] = bookData;
    dic[@"data"] = params;
    [self.bridge callHandler:@"addressBookPeopleList" data:dic responseCallback:^(id response) {
        
    }];
    
}



- (id)shareAppWithImageData:(id)params {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           NSDictionary *data = params[@"data"];
                           NSString* imagebase64data = nil;
                           if (!((NSDictionary *)data == nil || [(NSDictionary *)data count] == 0)) {
                               imagebase64data = data[@"imgData"];
                           }
                           if (params[@"type"]) {
                               NSArray *array = params[@"type"];
                               NSString* shareAimList = [array componentsJoinedByString:@","];
                               if (imagebase64data && imagebase64data.length > 0) {//有base64数据的
                                   NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:imagebase64data options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
                                   UIImage *decodedImage = [UIImage imageWithData: decodeData];
                                   if (decodedImage) {
                                   }
                               }
                           }
                       });
    });
    return @{@"msg":@"shareAppWithImageData:ok"};
}
- (id)shareAppAction:(id)params {
    
    WEAKSELF
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           [weakSelf shareAppNewAction:params];
                       });
    });
    
    
    return @{@"msg":@"shareApp:ok"};
}


- (id)shareAppBtn:(id)params {
    
    WEAKSELF
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           
                           NSDictionary *data = params[@"data"];
                           
                           if (!((NSDictionary *)data == nil || [(NSDictionary *)data count] == 0)) {
                               weakSelf.shareUrl = data[@"url"];
                               weakSelf.shareImageUrl = data[@"imgUrl"];
                               weakSelf.shareTitle = data[@"title"];
                               weakSelf.shareContent = data[@"content"];
                               weakSelf.isShowImage =  [data boolForKey:@"isShareImage"];
                           }
                           
                           if ([params[@"share"] boolValue]) {
                               UIImage *image = [UIImage imageNameFromBaseBuddle:@"分享"];
                               weakSelf.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(displayShareAppBtn)];
                           }else{
                               weakSelf.navigationItem.rightBarButtonItem = nil;
                           }
                           
                           if (params[@"type"]) {
                               NSArray *array = params[@"type"];
                               weakSelf.shareAimList = [array componentsJoinedByString:@","];
                           }
                       });
        
    });
    
    
    return @{@"msg":@"shareApp:ok"};
}

- (void)displayShareAppBtn {

    NSString *string;
    if ([self.shareUrl rangeOfString:@"?"].location == NSNotFound) {
        string = [NSString stringWithFormat:@"%@?invUserId=%ld", self.shareUrl, [[[self getUserInfo]valueForKey:@"UserCode"]integerValue]];
    }else {
        string = [self.shareUrl stringByReplacingOccurrencesOfString:@"?" withString:[NSString stringWithFormat:@"?invUserId=%ld&", [[[self getUserInfo]valueForKey:@"UserCode"]integerValue]]];
    }
    if(self.isShowImage){//走单独的图片分享
        [self.bridge callHandler:@"sharePageImage" data:nil responseCallback:^(id responseData) {
            NSString* imagebase64data = responseData[@"imgData"];
            UIImage * icon = nil;
            if ([JFStringHelper isNotEmpty:imagebase64data]) {
                NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:imagebase64data options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
                if (decodeData) {
                    icon = [UIImage imageWithData: decodeData];
                }
            }
            if (icon) {
            }
        }];
    }else{//走
    }

}

- (id)shareAppLink:(id)params {
    
    WEAKSELF
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           
                           NSDictionary *data = params[@"data"];
                           NSString * shareUrl;
                           NSString * shareImageUrl;
                           NSString * shareTitle;
                           NSString * shareContent;
                           if (!((NSDictionary *)data == nil || [(NSDictionary *)data count] == 0)) {
                                  shareUrl = data[@"url"];
                                  shareImageUrl = data[@"imgUrl"];
                                  shareTitle = data[@"title"];
                                  shareContent = data[@"content"];
                           }
                           
                           if (params[@"type"]) {
                               NSArray *array = params[@"type"];
                               NSString * shareAimList = [array componentsJoinedByString:@","];
                               
                               SDWebImageManager * manager = [SDWebImageManager sharedManager];
                               __block UIImage *icon = nil;
                               if ([[manager imageCache] imageFromMemoryCacheForKey:shareImageUrl]) {
                                   icon = [[manager imageCache] imageFromMemoryCacheForKey:shareImageUrl];
                               }else if ([[manager imageCache] imageFromDiskCacheForKey:shareImageUrl]) {
                                   icon = [[manager imageCache] imageFromDiskCacheForKey:shareImageUrl];
                               }
                               NSString* imagebase64data = data[@"imgData"];
                               if ([JFStringHelper isNotEmpty:imagebase64data]) {
                                   NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:imagebase64data options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
                                   if (decodeData) {
                                       icon = [UIImage imageWithData: decodeData];
                                   }
                               }
                               if (!icon) {
                                   [manager.imageDownloader downloadImageWithURL:[NSURL URLWithString:shareImageUrl] options:SDWebImageDownloaderProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                                       
                                   } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                                       
                                       if (finished) {
                                           icon = image;
                                           if(!image){
                                               icon = [UIImage imageNameFromBaseBuddle:@"AppIcon120.png"];
                                           }
                                       }
                                   }];
                               }else{
                               }
                           }
                       });
        
    });
    
    
    return @{@"msg":@"shareLink:ok"};
}


- (id)openInBrowser:(id)params{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           NSString *url = params[@"url"];
                           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                       });
    });
    return @{@"msg":@"openInBrowser:ok"};
}
-(void)giftStockShare:(NSDictionary*)dict{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
                           msg.from = @"BASE";
                           msg.to = @"STOCK";
                           msg.requestNum = @"800012";
                           msg.params = dict;
                           [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
                           
                       });
    });

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"msg"] = @"giftStockShare:ok";
    [self.bridge callHandler:@"giftStockShare" data:dic responseCallback:^(id response) {
        
    }];
}
//控制导航栏
- (id)updateNav:(id)params{
    BOOL hide = [params boolForKey:@"isHide"];
    self.hideNav = hide;
    if (!self.wkWebView.title) {
        [self.wkWebView reload];
    }
    [self creatLeftBtn];
    [self.navigationController setNavigationBarHidden:self.hideNav animated:YES];
    return @{@"msg":@"updateNav:ok"};
}
- (id)hideRightBtn:(id)params{
    self.navigationController.navigationItem.rightBarButtonItem = nil;
    return @{@"msg":@"hideRightBtn:ok"};
}
- (id)jumpPage:(id)params{
    
    if ([params[@"name"] isEqualToString:@"market"])
    {
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"STOCK";
        msg.requestNum = @"800000";
        msg.params = params;
       [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    }else if ([params[@"name"] isEqualToString:@"user_home"]) {
        NSDictionary *dic = params[@"data"];
        [JFJumpManage jumpUserHomeWithUserId:[dic[@"friendId"] longLongValue]];
    }
    else if ([params[@"name"] isEqualToString:@"bind-phone"]) {  //绑定手机号码
        JFMsgCenterVo * msg2 = [[JFMsgCenterVo alloc] init];
        msg2.from = @"BASE";
        msg2.to = @"USER";
        msg2.requestNum = @"400034";
        [JFMsgCenteManager requestWithMsgCenterVo:msg2 callback:^(JFResultVo *resultVo) {
        }];
    }
    else if ([params[@"name"] isEqualToString:@"information"]) {
      [[NSNotificationCenter defaultCenter] postNotificationName:kJFInfoMainViewShowNotification object:nil];
    }
    else if ([params[@"name"] isEqualToString:@"profile-page"]) {    // 首次上传头像,完善个人资料
        JFMsgCenterVo * msg2 = [[JFMsgCenterVo alloc] init];
        msg2.from = @"BASE";
        msg2.to = @"USER";
        msg2.requestNum = @"400010";
        [JFMsgCenteManager requestWithMsgCenterVo:msg2 callback:^(JFResultVo *resultVo) {
        }];
    }
    else if ([params[@"name"] isEqualToString:@"stock-circle"]) {    //股票圈
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.to = @"DIS";
        msg.from = @"BASE";
        msg.requestNum = @"900002";
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    }
    else if ([params[@"name"] isEqualToString:@"feedback"]) {//反馈建议
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.to = @"APP";
        msg.from = @"BASE";
        msg.requestNum = @"000014";
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    }
    else if ([params[@"name"] isEqualToString:@"add-buddy"]) {//添加好友
//        GZFriendsController *firendsVC = [[GZFriendsController alloc] init];
//        firendsVC.hidesBottomBarWhenPushed = YES;
//        self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"", nil) style:UIBarButtonItemStylePlain target:nil action:nil];
//        [self.navigationController pushViewController:firendsVC animated:YES];
    }
    else if ([params[@"name"] isEqualToString:@"we-media-square"]) {//自媒体提问
//        SLAdviserMainViewController *vc = [[SLAdviserMainViewController alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([params[@"name"] isEqualToString:@"trade"]) {//交易
      [[NSNotificationCenter defaultCenter] postNotificationName:kJFTradeMainViewShowNotification object:nil];
    }
    else if ([params[@"name"] isEqualToString:@"change-trade-pwd"]) {//修改初始交易密码
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"BASE";
        msg.to = @"USER";
        msg.requestNum = @"400009";
        msg.params = @{@"isTrade":@(1)};
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    }
    else if ([params[@"name"] isEqualToString:@"trade-page"]) {//修改初始交易密码
        NSDictionary *userInfo = params[@"data"];

        NSString *assetId = userInfo[@"stockCode"];
        NSString *stockName = userInfo[@"stockName"];
        NSNumber *stockType = userInfo[@"stockType"];
        NSNumber *isBuy = userInfo[@"isBuy"];

        NSString *stype = nil;

        if ([stockType stringValue].length) {
            stype = [stockType stringValue];
        }
        else{
            stype = ([[[assetId componentsSeparatedByString:@"."] lastObject] isEqualToString:@"HK"] == YES) ? @"64" : @"120";
        }

        NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
        dict[@"stockCode"] = assetId;
        dict[@"stockName"] = stockName;
        dict[@"stockType"] = stype;
        dict[@"isBuy"] = isBuy;
        
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"JFBASE";
        msg.to = @"STOCK";
        msg.requestNum = @"800015";
        msg.params = @{@"data":[dict copy]};
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    }else if ([params[@"name"] isEqualToString:@"to_apply"]) {//跳转原生去认购
            NSDictionary *userInfo = params[@"data"];
            NSString *assetId = userInfo[@"stockCode"];
            NSString *stockName = userInfo[@"stockName"];
            NSNumber *stockType = userInfo[@"stockType"];
            NSString *stype = nil;

            if ([stockType stringValue].length) {
                stype = [stockType stringValue];
            }
            else{
                stype = ([[[assetId componentsSeparatedByString:@"."] lastObject] isEqualToString:@"HK"] == YES) ? @"64" : @"120";
            }

            NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
            dict[@"stockCode"] = assetId;
            dict[@"stockName"] = stockName;
            dict[@"stockType"] = stype;
            
            JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
            msg.from = @"JFBASE";
            msg.to = @"STOCK";
            msg.requestNum = @"800020";
            msg.params = @{@"data":[dict copy],@"ActionType":@"1"};
            [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
        
    }else if ([params[@"name"] isEqualToString:@"ipo_stk_detail"]) {//跳转到新股详情
            NSDictionary *userInfo = params[@"data"];
            NSString *assetId = userInfo[@"stockCode"];
            NSString *stockName = userInfo[@"stockName"];
            NSNumber *stockType = userInfo[@"stockType"];
            NSString *stype = nil;

            if ([stockType stringValue].length) {
                stype = [stockType stringValue];
            }
            else{
                stype = ([[[assetId componentsSeparatedByString:@"."] lastObject] isEqualToString:@"HK"] == YES) ? @"64" : @"120";
            }

            NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
            dict[@"stockCode"] = assetId;
            dict[@"stockName"] = stockName;
            dict[@"stockType"] = stype;
            
            JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
            msg.from = @"JFBASE";
            msg.to = @"STOCK";
            msg.requestNum = @"800020";
            msg.params = @{@"data":[dict copy],@"ActionType":@"2"};
            [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
        
    } else if ([params[@"name"] isEqualToString:@"apply_notes"]) {//跳转原生去认购认购记录
        JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
        msg.from = @"JFBASE";
        msg.to = @"STOCK";
        msg.requestNum = @"800021";
        msg.params = @{};
        [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    }

    return @{@"msg":@"jumpPage:ok"};
}
- (id)closeWebView{
    [self back];
    return @{@"msg":@"closeWebView:ok"};
}

- (NSDictionary*)getDeviceInfo {
    return [JFDeviceInfo deviceDictionary];
}
- (NSDictionary *)getMobileInfo{
    
    NSDictionary * dict = [JFDeviceInfo SLDeviceInfoDictionary];
    NSMutableDictionary * multDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    if ([JFDeviceInfo isBenBen]) {
        multDict[@"displayName"] = @"玖富犇犇";
    }else{
        multDict[@"displayName"] = @"玖富股票";
    }
    return @{
             
             @"msg":@"getMobileInfo:Ok",
             @"data":multDict
             };
    
}

- (NSDictionary *)getUserInfo {
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    
    NSDate *startDate = [NSDate date];
    
    JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
    msg.from = @"BASE";
    msg.to = @"USER";
    msg.requestNum = @"400003";
    JFMsgCenterVo * data = [JFMsgCenteManager requestWithMsgCenterVo:msg callback:^(JFResultVo *resultVo) {
    }];
    NSString * sessionID = nil;
    if(data.params){
        sessionID = data.params[@"sessionID"];
    }

    dict[@"sessionId"]=sessionID;

    JFMsgCenterVo * msg2 = [[JFMsgCenterVo alloc] init];
    msg2.from = @"BASE";
    msg2.to = @"USER";
    msg2.requestNum = @"400005";
    JFMsgCenterVo * data2 = [JFMsgCenteManager requestWithMsgCenterVo:msg2 callback:^(JFResultVo *resultVo) {
    }];

    if(data2.params){
        NSDictionary * tempDict = data2.params[@"userInfo"];
        dict[@"UserId"] = tempDict[@"userId"];
        dict[@"UserCode"] = tempDict[@"userCode"];
        dict[@"nickName"] = tempDict[@"username"];
        dict[@"phoneNumber"] = tempDict[@"phoneNum"];
        dict[@"avatorUrlString"] = tempDict[@"avatorUrlString"];
        NSDictionary *ef07000001VO = tempDict[@"ef07000001VO"];
        if (ef07000001VO) {
            dict[@"hkLive"] = [ef07000001VO[@"hkLive"]boolValue]? @"true":@"false";
            dict[@"usLive"] = [ef07000001VO[@"usLive"]boolValue]? @"true":@"false";
        }
    }

    dict[@"equipmentNum"] = [JFDeviceInfo deviceIdentifier];
    dict[@"equipmentName"] = [[UIDevice currentDevice] name];
    dict[@"skin"] = [[AWThemeManager shareInstance].skinName lowercaseString];
    dict[@"language"] = [JFInternationalHelper currentLanguage];
    dict[@"upOrDownColor"] = @([[NSUserDefaults standardUserDefaults] integerForKey:@"AW_tradeKLineStyle_JF"]);
    
    NSDate *endDate = [NSDate date];
    NSLog(@"AlanWangcostTime = %f", [endDate timeIntervalSinceDate:startDate]);

    return @{
             @"msg":@"getUserInfo:Ok",
             @"data": dict,
             };
}
// 多重认证
- (id)openTrade {
    WEAKSELF
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                            [weakSelf back];
                           if (weakSelf.callBack) {
                               weakSelf.callBack(@1);
                           }
                          
                       });
    });
    return @{@"msg":@"openTrade:ok"};
}
- (id)jumpUrl:(id)params{
    WEAKSELF
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           
                           NSString *url = params[@"url"];
                           NSString *title = params[@"title"];
                           JFBaseWebViewController *surevc = [[JFBaseWebViewController alloc] init];
                           surevc.urlStr = url;
                           if(title){
                               surevc.webtitle = title;
                           }
                           surevc.backStyle =   JFWebLeftItemStyleBack | JFWebLeftItemStyleClose;
                           surevc.hidesBottomBarWhenPushed = !([(NSNumber *)params[@"bottomTab"] boolValue]);
                           surevc.hideNav  = !([((NSNumber *)params[@"isNeedHeader"]) boolValue]);
                           [weakSelf.navigationController pushViewController:surevc animated:YES];
                           
                       });
        
    });
    
    
    return @{@"msg":@"jumpUrl:ok"};
}
-(id)hideLeftBtn{
    WEAKSELF
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           weakSelf.navigationItem.leftBarButtonItems = nil;
                           weakSelf.navigationItem.leftBarButtonItem = nil;
                           weakSelf.navigationItem.backBarButtonItem = nil;
                           weakSelf.navigationItem.hidesBackButton = YES;
                       });
        
    });
    return @{@"msg":@"hideleftBtn:ok"};
}
- (id)saveImg:(id)params {
    NSString *imageString = [params objectForKey:@"imgData"];
    NSData *data = [[NSData alloc]initWithBase64EncodedString:imageString options:0];
    [self saveImageFinished:[UIImage imageWithData:data]];
    return @{@"msg":@"saveImg:ok"};
}
- (id)shareAppNewAction:(id)params {
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           NSDictionary *data = params[@"data"];
                           NSString * shareUrl = @"";
                           NSString * shareImageUrl = @"";
                           NSString * shareTitle = @"";
                           NSString * shareContent = @"";
                           if (!((NSDictionary *)data == nil || [(NSDictionary *)data count] == 0)) {
                               shareUrl = data[@"url"];
                               shareImageUrl = data[@"imgUrl"];
                               shareTitle = data[@"title"];
                               shareContent = data[@"content"];
                           }
                           if (params[@"type"]) {
                               NSArray *array = params[@"type"];
                               NSString * shareTypeList = [array componentsJoinedByString:@","];
                               SDWebImageManager * manager = [SDWebImageManager sharedManager];
                               __block UIImage *icon = nil;
                               if ([[manager imageCache] imageFromMemoryCacheForKey:shareImageUrl]) {
                                   icon = [[manager imageCache] imageFromMemoryCacheForKey:shareImageUrl];
                               }else if ([[manager imageCache] imageFromDiskCacheForKey:shareImageUrl]) {
                                   icon = [[manager imageCache] imageFromDiskCacheForKey:shareImageUrl];
                               }
                               NSString* imagebase64data = data[@"imgData"];
                               if ([JFStringHelper isNotEmpty:imagebase64data]) {
                                   NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:imagebase64data options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
                                   if (decodeData) {
                                        icon = [UIImage imageWithData: decodeData];
                                   }
                               }
                               
                               if (!icon) {
                                   [manager.imageDownloader downloadImageWithURL:[NSURL URLWithString:shareImageUrl] options:SDWebImageDownloaderProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                                       
                                   } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                                       
                                       if (finished) {
                                           icon = image;
                                           if(!image){
                                               icon = [UIImage imageNameFromBaseBuddle:@"AppIcon120.png"];
                                           }
                                       }
                                   }];
                               }else{
                               }
                           }
                       });
    
    return @{@"msg":@"shareAppNewAction:ok"};
}
#pragma mark--辅助方法
- (void)saveImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}
#pragma mark - CameraOverlayView

- (UIView *) CameraOverlayView:(NSString *)tips type:(NSUInteger)type
{
    CGFloat height = SCREEN_HEIGHT;
    CGFloat width = SCREEN_WIDTH;
    
    UIView *viewBg = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    viewBg.backgroundColor = [UIColor clearColor];
    //view旋转
    viewBg.transform = CGAffineTransformIdentity;
    [viewBg setTransform:CGAffineTransformMakeRotation(M_PI/2)];
    
    
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(- 80, height * 0.3, width + 80, height * 0.4)];
    
    
    if (type == 1) {
        imageV.image = JFBaseBuddleImage(@"icon_idcardF");
    }else if (type == 2){
        imageV.image = JFBaseBuddleImage(@"icon_idcardB");
    }else{
        imageV.clipsToBounds = YES;
        imageV.layer.borderColor = [UIColor clearColor].CGColor;
        imageV.layer.borderWidth = 1;
        imageV.layer.cornerRadius = 2.f;
    }
    
    
    [viewBg addSubview:imageV];
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(-80, imageV.frame.origin.y - 25, width + 80, 20)];
    label.textAlignment = NSTextAlignmentCenter;
    if (tips) {
        if (type == 1) {
            
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[JFStringHelper internationalString:@"请拍摄身份证人像面，切勿超出拍摄框边缘。"] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize: 12.5],NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]}];
            
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            [paragraphStyle setAlignment:NSTextAlignmentCenter];
            [string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
            
            [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:198/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(6, 3)];
            
            [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:198/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(14, 5)];
            
            label.attributedText = string;
            
            
        }else if (type == 2){
            
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[JFStringHelper internationalString:@"    请拍摄身份证国徽面，切勿超出拍摄框边缘。"] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize: 12.5],NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]}];
            
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            [paragraphStyle setAlignment:NSTextAlignmentCenter];
            [string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
            
            [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:198/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(7, 3)];
            
            [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:198/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(15, 5)];
            
            label.attributedText = string;
            
        }else{
            label.text = tips;
        }
        
    }else{
        label.text = !(tips.length == 0 || tips== nil ) ? tips : @"请将身份证或银行卡完全放入矩形框内,确保无反光、变形";
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor colorWithHexString:@"#ffffff"];
        label.layer.cornerRadius = 10.f;
        label.layer.backgroundColor = [UIColor colorWithHexString:@"#999999"].CGColor;
    }
    
    [viewBg addSubview:label];
    
    return viewBg;
    
}

-(void)didCaptureItem:(NSNotification *)noti
{
    
    _pickerVC.cameraOverlayView.hidden = YES;
    
}

-(void)didRejectItem:(NSNotification *)noti
{
    
    _pickerVC.cameraOverlayView.hidden = NO;//[self CameraOverlayView];
    
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    image = [self fixOrientation:image];
    NSData *data = UIImageJPEGRepresentation(image,0.1);
    NSString *pictureDataString=[data base64EncodedStringWithOptions:0];
    
    [self.bridge callHandler:@"picUpload" data:@{@"pic":pictureDataString} responseCallback:^(id response) {

    }];
    
    [self.bridge callHandler:@"JFNewClient_Back" data:@{
                                                      
                                                      @"msg":@"useSysCamera:ok",
                                                      @"data":pictureDataString
                                                      
                                                      } responseCallback:^(id responseData)
     {
         
     }];
    
}
- (UIImage *)fixOrientation:(UIImage*)image {
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    
    if (image.imageOrientation == UIImageOrientationUp) {
        return image;
        
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL,
                                             image.size.height,
                                             image.size.width,
                                             CGImageGetBitsPerComponent(image.CGImage),
                                             0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage)
                                             );
    
    
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

//用户取消拍照
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark--系统方法
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (!self.wkWebView.title) {
        [self.wkWebView reload];
    }
    [self creatLeftBtn];
    self.hideNav = _hideNav;
    [self.navigationController setNavigationBarHidden:self.hideNav animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)dealloc {
    if (_wkWebView) {
        [_wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"AWCallNative"];
    }
    [_wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_wkWebView removeObserver:self forKeyPath:@"title"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [_wkWebView stopLoading];
    _wkWebView.UIDelegate = nil;
    _wkWebView.navigationDelegate = nil;
}
#pragma mark 版本适配
- (void)keyBoardShow {
    CGPoint point = self.wkWebView.scrollView.contentOffset;
    self.keyBoardPoint = point;
}
/// 键盘将要隐藏
- (void)keyBoardHidden {
    self.wkWebView.scrollView.contentOffset = self.keyBoardPoint;
    
    if (@available(iOS 11.4, *)) {
        WKWebView *webview = (WKWebView*)self.wkWebView;
        for(UIView* v in webview.subviews){
            if([v isKindOfClass:NSClassFromString(@"WKScrollView")]){
                UIScrollView *scrollView = (UIScrollView*)v;
                [scrollView setContentOffset:CGPointMake(0, 0)];
            }
        }
    }
}

@end
